import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {NzContextMenuService, NzMessageService, NzModalService} from 'ng-zorro-antd';
import {FileManagementService} from '../file-management.service';
import {CommonTool} from '../../../common/common.tool';
import {environment} from '../../../../environments/environment';
import {FolderReq} from '../file-management.model';
import {UploadFileComponent} from '../../../common/upload-file/upload-file.component';
import {HTTP_URLS} from '../../../base/base-http.url';
import {MusicPlayerComponent} from '../../../common/music-player/music-player.component';

@Component({
  selector: 'app-file-management',
  templateUrl: './file-management-default.component.html',
  styleUrls: ['./file-management-default.component.scss']
})
export class FileManagementDefaultComponent implements OnInit {

  @ViewChild(UploadFileComponent, {static: true})
  public uploadFileComponent: UploadFileComponent;
  @ViewChild(MusicPlayerComponent, {static: true})
  public musicPlayerComponent: MusicPlayerComponent;
  public tableModel: Array<any>;
  public isFolderVisible: boolean;
  public folderValidateStatus: any;
  public folderOkDisabled: any;
  public folderInfo: FolderReq;
  public checkedModel: any;
  public isAllChecked: boolean;
  public labelModel: Array<any>;
  public currentObj: any;
  public isChecked: boolean;
  public environment = environment;
  public isShareVisible: boolean;
  public isUrlVisible: boolean;
  public shareUrl: string;
  public drawCode: string;
  public shearList: Array<any>;
  public fileName: string;
  public isUpdateVisible: boolean;
  public updateOkDisabled: boolean;
  public updateValidateStatus: any;
  public fileFolder: any;
  public movieData: Array<object> = [];
  public needCode: string;
  public validTime: string;
  public updateShareOkDisabled: boolean;
  public fileTypeStatus;
  public validTimeStatus;
  public showVideoPlay = false;
  public videoUrl: string;
  public showMusicPlay = false;
  public picturePlay = false;
  public pictureUrl;
  public isCopy;
  public isDev = false;
  public isDevVisible = false;
  public devUrl;


  constructor(private nzContextMenuService: NzContextMenuService,
              public fileManagementService: FileManagementService,
              public commonTool: CommonTool,
              private modalService: NzModalService,
              public ele: ElementRef,
              private message: NzMessageService) {
    this.isFolderVisible = false;
    this.isShareVisible = false;
    this.isUpdateVisible = false;
    this.isUrlVisible = false;
    this.updateShareOkDisabled = true;
    this.folderOkDisabled = true;
    this.updateOkDisabled = true;
    this.folderInfo = new FolderReq();
    this.labelModel = [];
    this.tableModel = [];
    this.currentObj = {id: 0, parentId: 'root', fileId: ''};
    this.checkedModel = {};
    this.isChecked = true;
    this.shearList = [];
    this.fileName = '';
    this.fileTypeStatus = '';
    this.validTimeStatus = '';
    this.fileFolder = {};
    this.movieData = [];
    for (const data of this.environment.config.video) {
      this.movieData.push({
        path: this.environment.config.url + data.path,
        origin: this.environment.config.url + data.origin
      });
    }
  }

  // 初始化
  ngOnInit(): void {
    this.getData();
  }

  public validTimeNotNull(data) {
    if (this.commonTool.notNull(data)) {
      this.validTimeStatus = '';
    } else {
      this.validTimeStatus = 'error';
    }
    if (this.commonTool.notNull(data) && this.commonTool.notNull(this.needCode)) {
      this.updateShareOkDisabled = false;
    } else {
      this.updateShareOkDisabled = true;
    }
  }

  public fileTypeNotNull(data) {
    if (this.commonTool.notNull(data)) {
      this.fileTypeStatus = '';
    } else {
      this.fileTypeStatus = 'error';
    }
    if (this.commonTool.notNull(data) && this.commonTool.notNull(this.validTime)) {
      this.updateShareOkDisabled = false;
    } else {
      this.updateShareOkDisabled = true;
    }
  }

  /**
   * 获取后缀
   */
  public getSuffix(name) {
    let suffix = '';
    if (this.commonTool.notNull(name)) {
      suffix = name.substring(name.lastIndexOf('.'), name.length);
    }
    return suffix.toLowerCase();
  }


  /**
   * 视频播放
   */
  public videoPlay(data) {
    this.fileManagementService.downloadFile(data['id']).subscribe(res => {
      this.showVideoPlay = true;
      this.videoUrl = res['url'];
    });
  }

  /**
   * 播放音乐
   */
  public videoMusic(data, bool) {
    if (bool) {
      this.showMusicPlay = true;
      const id = this.musicPlayerComponent.addMusic({
        name: data['name'],
        id: data['id']
      });
      this.musicPlayerComponent.play(id);
      this.musicPlayerComponent.isPlayList = false;
    } else {
      this.musicPlayerComponent.addMusic({
        name: data['name'],
        id: data['id']
      });
    }
  }

  /**
   * 添加播放列表
   */
  public batchPlay() {
    this.showMusicPlay = true;
    for (const key in this.checkedModel) {
      if (this.getSuffix(this.checkedModel[key].name) === '.mp3') {
        this.musicPlayerComponent.addMusic({
          name: this.checkedModel[key]['name'],
          id: this.checkedModel[key]['id']
        });
      }
    }
  }


  public createCdn(data) {
    const suffix = this.getSuffix(data.name);
    this.isDevVisible = true;
    this.devUrl = HTTP_URLS.downloadDev + data['id'] + suffix + '?open=0';
  }

  /**
   * 打开图片
   */
  public openPicture(data) {
    this.fileManagementService.downloadFile(data['id']).subscribe(res => {
      this.picturePlay = true;
      this.pictureUrl = res['url'];
    });
  }

  // 验证文件目录输入框
  public validateFolderInput(data) {
    if (!this.commonTool.notNull(data)) {
      this.folderValidateStatus = 'error';
      this.folderOkDisabled = true;
      return;
    }
    const pattern = new RegExp('[/\\\\:*?"<>|]');
    if (pattern.test(data)) {
      this.folderValidateStatus = 'error';
    } else {
      this.folderOkDisabled = false;
      this.folderValidateStatus = '';
    }
  }

  public validateUpdateInput(data) {
    if (!this.commonTool.notNull(data)) {
      this.updateValidateStatus = 'error';
      this.updateOkDisabled = true;
      return;
    }
    const pattern = new RegExp('[/\\\\:*?"<>|]');
    if (pattern.test(data)) {
      this.updateValidateStatus = 'error';
    } else {
      this.updateOkDisabled = false;
      this.updateValidateStatus = '';
    }
  }

  /**
   * 剪切
   */
  public shear() {
    this.shearList = [];
    if (!this.commonTool.notNull(this.checkedModel)) {
      this.message.success('你还没有选择数据哦！');
      return;
    }
    // tslint:disable-next-line:forin
    for (const key in this.checkedModel) {
      const data = this.checkedModel[key];
      this.shearList.push({
        id: data.id,
        isFile: data.isFile,
        parentId: data.parentId
      });
    }
  }

  /**
   * 粘贴
   */
  public paste(isCopy) {
    if (!this.commonTool.notNull(this.shearList)) {
      this.message.success('你的粘贴板没有数据哦！');
      return;
    }
    for (const shear of this.shearList) {
      shear.parentId = this.currentObj.id;
    }
    if (isCopy) {
      this.fileManagementService.copyFileFolder(this.shearList).subscribe(() => {
        this.getData({id: this.currentObj.id});
      });
    } else {
      this.fileManagementService.moveFileFolder(this.shearList).subscribe(() => {
        this.getData({id: this.currentObj.id});
      });
    }
  }

  /**
   * 编辑
   */
  public edit($event, data) {
    this.fileName = data.name;
    $event.stopPropagation();
    this.updateOkDisabled = false;
    this.isUpdateVisible = true;
    this.fileFolder = data;
  }

  /**
   * 修改文件名称
   */
  public updateFileFolder() {
    if (this.fileFolder.isFile) {
      this.fileManagementService.updateFile(this.fileFolder.id, {
        name: this.fileName
      }).subscribe(() => {
        this.isUpdateVisible = false;
        this.shearList = [];
        this.getData({id: this.currentObj.id});
      });
    } else {
      this.fileManagementService.updateFolder(this.fileFolder.id, {
        name: this.fileName
      }).subscribe(() => {
        this.isUpdateVisible = false;
        this.shearList = [];
        this.getData({id: this.currentObj.id});
      });
    }

  }

  fileShareCancel() {
    this.isShareVisible = false;
    this.needCode = undefined;
    this.validTime = undefined;
    this.validTimeStatus = '';
    this.fileTypeStatus = '';
  }

  /**
   * 分享文件
   */
  public fileShare(data) {
    this.fileManagementService.createShareFile({
      folderFiles: this.shearList,
      needCode: this.needCode,
      validTime: this.validTime
    }).subscribe((res) => {
      this.isShareVisible = false;
      this.shareUrl = location.origin + '/#/share/' + res.code;
      this.drawCode = res.drawCode;
      this.isUrlVisible = true;
      this.needCode = undefined;
      this.validTime = undefined;
    });
  }

  public downloadFile(id) {
    this.fileManagementService.downloadFile(id).subscribe(res => {
      location.href = res['url'];
    });
  }

  // 确认创建弹窗
  public createFolderOk(currentObj) {
    this.isFolderVisible = false;
    this.fileManagementService.createFolder({
      name: this.folderInfo.name,
      parentId: currentObj.id
    }).subscribe(res => {
      this.modalService.success({
        nzTitle: '创建目录',
        nzContent: '操作成功！',
        nzOnOk: () => {
          this.folderInfo.name = '';
          this.isFolderVisible = false;
        }
      });
      this.getData(currentObj);
    });
  }


  // 标签点击事件
  public label(data, index) {
    if (data.id === 'root' && index === 0) {
      this.labelModel = [];
    }
    this.labelModel.splice(index + 1, this.labelModel.length - (index + 1));
    if (this.labelModel.length === 0 && data.name === 'dev') {
      this.isDev = true;
    } else {
      let bool = false;
      for (const label of this.labelModel) {
        if (label.name === 'dev') {
          bool = true;
        }
      }
      this.isDev = bool;
    }
    this.getData(data);
  }

  // 获取数据
  public getData(data?) {
    this.checkedModel = [];
    this.isAllChecked = false;
    this.tableModel = [];
    if (!this.commonTool.notNull(data)) {
      data = {};
    }
    if (!this.commonTool.notNull(data.id)) {
      data.id = 'root';
    }
    this.currentObj = data;
    this.fileManagementService.getFolders({parentId: data.id}).subscribe(res => {
      const array = [];
      for (const arr of res['folders']) {
        if (this.labelModel.length === 0 && arr.name === 'dev') {
          arr.desc = '开发者目录';
        }
        arr.isFile = false;
        array.push(arr);
      }
      for (const r of res['files']) {
        r.isFile = true;
        array.push(r);
      }
      this.tableModel = array;
    });
  }

  // 点击
  public trClick(event, data) {
    if (!data.isFile) {
      if (this.labelModel.length === 0 && data.name === 'dev') {
        this.isDev = true;
      }
      this.labelModel.push(data);
      this.getData(data);
    }
  }

  // 选择
  public checkboxChoice(data) {
    // 全部选择
    this.isAllChecked = this.tableModel.every((item) => {
      return this.checkedModel[item.id];
    });
    // 设置选中后可以操作的按钮
    this.isChecked = true;
    this.tableModel.forEach(item => {
      if (this.checkedModel[item.id]) {
        this.isChecked = false;
      }
    });
    // 选中，取消
    if (this.checkedModel[data.id]) {
      this.checkedModel[data.id] = data;
    } else {
      delete this.checkedModel[data.id];
    }
  }

  // 全选
  public checkAll(value) {
    if (this.isAllChecked) {
      for (const folder of this.tableModel) {
        this.checkedModel[folder.id] = folder;
      }
      this.isChecked = false;
    } else {
      for (const folder of this.tableModel) {
        delete this.checkedModel[folder.id];
      }
      this.isChecked = true;
    }
  }

  // 排序
  public sort(event, ...events): void {
    for (const ev of events) {
      if (ev.nzSortKey !== event.key) {
        ev.nzSort = null;
      }
    }
    const array = this.tableModel;
    if (event.value === 'ascend') {
      if (event.key === 'name') {
        array.sort((a, b) => {
          return a[event.key].localeCompare(b[event.key], 'zh-CN');
        });
      } else if (event.key === 'updateTime') {
        array.sort((a, b) => {
          return new Date(a[event.key].replace(/-/g, '/')).getTime() - new Date(b[event.key].replace(/-/g, '/')).getTime();
        });
      } else if (event.key === 'size') {
        array.sort((a, b) => {
          return parseFloat(a[event.key]) - parseFloat(b[event.key]);
        });
      }
    } else if (event.value === 'descend') {
      array.reverse();
    } else {
      this.getData(this.currentObj);
    }
    this.tableModel = JSON.parse(JSON.stringify(array));
  }

  // 返回上级
  public revert() {
    if (this.labelModel.length <= 1) {
      this.getData({id: 'root'});
      this.labelModel.splice(this.labelModel.length - 1, 1);
      this.currentObj = {id: 'root'};
    } else {
      this.getData({id: this.currentObj.parentId});
      const data = this.labelModel.splice(this.labelModel.length - 1, 1);
      this.currentObj = data[0];
    }
    if (this.labelModel.length === 0 && this.currentObj.name === 'dev') {
      this.isDev = true;
    } else {
      let bool = false;
      for (const label of this.labelModel) {
        if (label.name === 'dev') {
          bool = true;
        }
      }
      this.isDev = bool;
    }
  }

  // 删除
  public delete(checkedModel) {
    this.modalService.confirm({
      nzTitle: '确认要删除文件吗?',
      nzContent: '<b style="color: red;">文件删除后将无法找回哦！</b>',
      nzOkText: '确认',
      nzOkType: 'danger',
      nzOnOk: () => {
        const fileIds = [];
        const folderIds = [];
        for (const key in checkedModel) {
          if (checkedModel[key].isFile) {
            fileIds.push(key);
          } else {
            folderIds.push(key);
          }
        }
        this.fileManagementService.deleteFolderByIds({folderIds, fileIds}).subscribe(res => {
          this.modalService.success({
            nzTitle: '删除',
            nzContent: '删除成功！',
            nzOnOk: () => {
            }
          });
          this.checkedModel = {};
          this.isAllChecked = false;
          this.isChecked = true;
          this.getData(this.currentObj);
        });
      },
      nzCancelText: '取消'
    });
  }

  // 分享
  public share() {
    if (!this.commonTool.notNull(this.checkedModel)) {
      this.message.success('你还没有选择数据哦！');
      return;
    }
    // tslint:disable-next-line:forin
    for (const key in this.checkedModel) {
      const data = this.checkedModel[key];
      this.shearList.push({
        id: data.id,
        isFile: data.isFile,
        parentId: data.parentId
      });
    }
  }


  // 上传文件目录
  public uploadFolder() {
    const $this = this;
    const input = document.createElement('input');
    input.setAttribute('multiple', '');
    input.setAttribute('webkitdirectory', '');
    input.type = 'file';
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
      $this.uploadFileComponent.uploadFileStart(e.target['files'], $this.currentObj.id, (data) => {
        if (data) {
          $this.getData($this.currentObj);
        }
      });
    };
  }

  // 上传
  public uploadFile() {
    const $this = this;
    const input = document.createElement('input');
    input.type = 'file';
    input.setAttribute('multiple', '');
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
      $this.uploadFileComponent.uploadFileStart(e.target['files'], $this.currentObj.id, (data) => {
        if (data) {
          $this.getData($this.currentObj);
        }
      });
    };
  }

  public playMovie(url) {
    this.showVideoPlay = true;
    this.videoUrl = url;
  }

  /**
   * 复制
   */
  public copy(data) {
    const input = document.createElement('input');
    input.value = data;
    document.body.appendChild(input);
    input.select();
    if (document.execCommand('Copy')) {
      this.message.success('复制成功！');
    } else {
      this.message.success('复制失败！');
    }
  }
}
